import { App, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { CsConnEntity } from '../entity/conn';
import { GameRoomInfoEntity } from '../entity/room';
import { Application as SocketApplication } from '@midwayjs/socketio';

/**
 * 连接
 */
@Provide()
export class CsConnService extends BaseService {
  @InjectEntityModel(CsConnEntity)
  csConnEntity: Repository<CsConnEntity>;

  @InjectEntityModel(GameRoomInfoEntity)
  GameRoomInfoEntity: Repository<GameRoomInfoEntity>;

  @App('socketIO')
  socketApp: SocketApplication;
  
  /**
   * 绑定
   * @param isAdmin
   * @param userId
   * @param connId
   */
  async binding(userId: number, connId: string) {
    const info = await this.csConnEntity.findOneBy({
      userId,
      type: 0,
    });
    if (info) {
      info.connId = connId;
      info.type = 0;
      await this.csConnEntity.update(info.id, { connId: connId });
    } else {
      const entity = new CsConnEntity();
      entity.userId = userId;
      entity.connId = connId;
      entity.type = 0;
      await this.csConnEntity.insert(entity);
    }
  }

  /**
   * 获得连接ID
   * @param roomId
   */
  async getConnId(userId) {
    const info = await this.csConnEntity.findOneBy({
      userId
    });
    return info ? info.connId : null;
  }

  /**
 * 发送消息
 * @param userId
 * @returns
 */
  async sendMessage(userId: string, msg: any) {
    if (!userId) return
    // 获得连接ID
    const connId = await this.getConnId(userId);
    this.socketApp.of('/socket').to(connId).emit('msg', msg);
  }
}
